package service

import (
	"log"
	"sync"
	"time"
)

// StopLossEvent 止损事件结构
type StopLossEvent struct {
	OrderID   int64     `json:"order_id"`   // 触发止损的订单ID
	Symbol    string    `json:"symbol"`     // 交易对
	LossRate  float64   `json:"loss_rate"`  // 亏损比例
	Timestamp time.Time `json:"timestamp"`  // 事件发生时间
}

// SupportLevelBreakdownEvent 支撑位跌破事件结构
type SupportLevelBreakdownEvent struct {
	Symbol        string    `json:"symbol"`         // 交易对
	SupportLevel  float64   `json:"support_level"`  // 支撑位价格
	CurrentPrice  float64   `json:"current_price"`  // 当前价格
	BreakdownRate float64   `json:"breakdown_rate"` // 跌破幅度
	Timestamp     time.Time `json:"timestamp"`      // 事件发生时间
}

// StopLossEventListener 止损事件监听器接口
type StopLossEventListener interface {
	OnStopLossTriggered(event StopLossEvent)
	OnSupportLevelBreakdown(event SupportLevelBreakdownEvent)
}

// StopLossEventService 止损事件通知服务
type StopLossEventService struct {
	listeners []StopLossEventListener
	mu        sync.RWMutex
}

// GlobalStopLossEventService 全局止损事件服务实例
var GlobalStopLossEventService *StopLossEventService

// InitStopLossEventService 初始化全局止损事件服务
func InitStopLossEventService() {
	GlobalStopLossEventService = &StopLossEventService{
		listeners: make([]StopLossEventListener, 0),
	}
	log.Println("[STOP_LOSS_EVENT] 止损事件服务已初始化")
}

// AddListener 添加事件监听器
func (ses *StopLossEventService) AddListener(listener StopLossEventListener) {
	ses.mu.Lock()
	defer ses.mu.Unlock()
	ses.listeners = append(ses.listeners, listener)
	log.Printf("[STOP_LOSS_EVENT] 已添加事件监听器，当前监听器数量: %d", len(ses.listeners))
}

// RemoveListener 移除事件监听器
func (ses *StopLossEventService) RemoveListener(listener StopLossEventListener) {
	ses.mu.Lock()
	defer ses.mu.Unlock()
	
	for i, l := range ses.listeners {
		if l == listener {
			ses.listeners = append(ses.listeners[:i], ses.listeners[i+1:]...)
			log.Printf("[STOP_LOSS_EVENT] 已移除事件监听器，当前监听器数量: %d", len(ses.listeners))
			break
		}
	}
}

// NotifyStopLossTriggered 通知止损事件触发
func (ses *StopLossEventService) NotifyStopLossTriggered(event StopLossEvent) {
	ses.mu.RLock()
	listeners := make([]StopLossEventListener, len(ses.listeners))
	copy(listeners, ses.listeners)
	ses.mu.RUnlock()
	
	log.Printf("[STOP_LOSS_EVENT] 通知止损事件: OrderID=%d, Symbol=%s, LossRate=%.2f%%, 监听器数量=%d", 
		event.OrderID, event.Symbol, event.LossRate*100, len(listeners))
	
	// 异步通知所有监听器
	for _, listener := range listeners {
		go func(l StopLossEventListener) {
			defer func() {
				if r := recover(); r != nil {
					log.Printf("[STOP_LOSS_EVENT] 监听器处理事件时发生错误: %v", r)
				}
			}()
			l.OnStopLossTriggered(event)
		}(listener)
	}
}

// NotifySupportLevelBreakdown 通知支撑位跌破事件
func (ses *StopLossEventService) NotifySupportLevelBreakdown(event SupportLevelBreakdownEvent) {
	ses.mu.RLock()
	listeners := make([]StopLossEventListener, len(ses.listeners))
	copy(listeners, ses.listeners)
	ses.mu.RUnlock()
	
	log.Printf("[SUPPORT_LEVEL_EVENT] 通知支撑位跌破事件: Symbol=%s, SupportLevel=%.6f, CurrentPrice=%.6f, BreakdownRate=%.2f%%, 监听器数量=%d", 
		event.Symbol, event.SupportLevel, event.CurrentPrice, event.BreakdownRate*100, len(listeners))
	
	// 异步通知所有监听器
	for _, listener := range listeners {
		go func(l StopLossEventListener) {
			defer func() {
				if r := recover(); r != nil {
					log.Printf("[SUPPORT_LEVEL_EVENT] 监听器处理支撑位跌破事件时发生错误: %v", r)
				}
			}()
			l.OnSupportLevelBreakdown(event)
		}(listener)
	}
}

// GetListenerCount 获取当前监听器数量
func (ses *StopLossEventService) GetListenerCount() int {
	ses.mu.RLock()
	defer ses.mu.RUnlock()
	return len(ses.listeners)
}